import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { RepairWorkflowService } from '../../services/repair-workflow.service';
import { RepairRequest, UserRole, Device, RepairPriority } from '../../models/repair-workflow.model';

@Component({
  selector: 'app-repair-request',
  templateUrl: './repair-request.component.html',
  styleUrls: ['./repair-request.component.scss']
})
export class RepairRequestComponent implements OnInit {
  requestForm: Partial<RepairRequest> = {
    deviceId: 0,
    title: '',
    description: '',
    faultDescription: '',
    deviceModel: '',
    priority: RepairPriority.MEDIUM,
    urgencyLevel: RepairPriority.MEDIUM
  };

  priorities = [
    { value: RepairPriority.LOW, label: '低', color: 'success' },
    { value: RepairPriority.MEDIUM, label: '中', color: 'warning' },
    { value: RepairPriority.HIGH, label: '高', color: 'danger' },
    { value: RepairPriority.CRITICAL, label: '紧急', color: 'dark' }
  ];

  urgencyLevels = [
    { value: RepairPriority.LOW, label: '低', color: 'success' },
    { value: RepairPriority.MEDIUM, label: '中', color: 'warning' },
    { value: RepairPriority.HIGH, label: '高', color: 'danger' },
    { value: RepairPriority.CRITICAL, label: '紧急', color: 'dark' }
  ];

  isSubmitting = false;
  currentUser$ = this.workflowService.currentUser$;

  constructor(
    private workflowService: RepairWorkflowService,
    private router: Router
  ) {}

  ngOnInit(): void {
    // 不再需要加载设备列表
  }

  onSubmit(): void {
    if (this.validateForm()) {
      this.isSubmitting = true;
      
      // 获取当前用户信息
      const currentUser = this.workflowService.getCurrentUser();
      
      const requestToSubmit: Partial<RepairRequest> = {
        ...this.requestForm,
        description: this.requestForm.faultDescription,
        priority: this.requestForm.urgencyLevel || this.requestForm.priority,
        requestedBy: currentUser?.fullName || 'Unknown',
        requestedByUserId: currentUser?.id
      };
      
      console.log('提交数据:', requestToSubmit); // 添加调试日志
      
      this.workflowService.createRepairRequest(requestToSubmit).subscribe({
        next: (request) => {
          console.log('维修申请创建成功:', request);
          
          // 启动工作流
          if (request.id) {
            this.workflowService.startWorkflow(request.id).subscribe({
              next: (response) => {
                this.isSubmitting = false; // 重置状态
                if (response && response.success) {
                  alert(`维修申请已提交成功！\n申请编号: ${request.id}\n工作流已启动`);
                  this.router.navigate(['/tasks']);
                } else {
                  alert('维修申请创建成功，但启动工作流失败');
                }
              },
              error: (error) => {
                console.error('启动工作流失败:', error);
                this.isSubmitting = false; // 重置状态
                alert('维修申请创建成功，但启动工作流失败');
              }
            });
          } else {
            this.isSubmitting = false; // 重置状态
            alert('维修申请创建成功，但无法获取申请ID');
          }
        },
        error: (error) => {
          console.error('创建维修申请失败:', error);
          this.isSubmitting = false; // 重置状态
          alert('创建维修申请失败，请重试');
        }
      });
    }
  }

  private validateForm(): boolean {
    if (!this.requestForm.deviceId || this.requestForm.deviceId <= 0) {
      alert('请输入有效的设备ID（正整数）');
      return false;
    }
    if (!this.requestForm.title?.trim()) {
      alert('请输入维修标题');
      return false;
    }
    if (!this.requestForm.deviceModel?.trim()) {
      alert('请输入设备型号');
      return false;
    }
    if (!this.requestForm.urgencyLevel) {
      alert('请选择紧急程度');
      return false;
    }
    if (!this.requestForm.faultDescription?.trim()) {
      alert('请输入故障描述');
      return false;
    }
    return true;
  }

  switchToAdmin(): void {
    this.workflowService.switchUserRole(UserRole.ADMIN);
  }

  switchToTechnician(): void {
    this.workflowService.switchUserRole(UserRole.TECHNICIAN);
  }

  trackByPriority(index: number, item: any): any {
    return item.value;
  }

  trackByUrgency(index: number, item: any): any {
    return item.value;
  }

  isUserRole(role: UserRole): boolean {
    const currentUser = this.workflowService.getCurrentUser();
    return currentUser?.role === role;
  }

  get UserRole() {
    return UserRole;
  }
} 